import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { changeMenu } from '@/utils/index'
import { resetRouter } from '@/router'
import request from '@/utils/request'
import router from "@/router/index";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    info: {},
    logo: 'https://k12.vipwfx.com/wxmini/static/hn_logo.png',
    avatar: 'https://k12.vipwfx.com/wxmini/static/hn_logo.png',
    update_index: [],
    routers: '',
    config_group: '',
    routersindex: 0,
    model: 'admin',
    edit: '',
    editId: '',
    IS_MUCH_SHOP: 0,
    menu: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_INFO: (state, info) => {
    state.info = info
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_IS_MUCH_SHOP: (state, token) => {
    state.IS_MUCH_SHOP = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_LOGO: (state, name) => {
    state.logo = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTERS: (state, routers) => {
    state.routers = routers
  },
  SET_ROUTERSINDEX: (state, routersindex) => {
    state.routersindex = routersindex
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_UPDATE_INDEX: (state, view) => {
    if(state.update_index.indexOf(view)<0)
      state.update_index.push(view)
  },
  SET_CONFIG_GROUP: (state, view) => {
      state.config_group=view
  },
  SET_MENU: (state, view) => {
      state.menu=view
  },
  SET_MODEL: (state, view) => {
      state.model=view
  },
  DEL_UPDATE_INDEX: (state, index) => {
    state.update_index.splice(index, 1); 
  },
  SET_EDIT: (state, info) => {
    state.edit = info
  },
  SET_EDITID: (state, info) => {
    state.editId = info
  },
}



const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      request.get("pub/UserInfo/index", {}, "post").then((res) => {
        if(res.list==undefined)return
        let list=[]
        let menu=[]
        let index=localStorage.getItem("menuindex")||1
        if(res.info.exp_times!=undefined&&res.info.exp_times.indexOf('已到期')>=0){
          let rout=changeMenu(res.list[1])
          list[1]=rout
          commit('SET_ROUTERSINDEX', 1)
          menu.push(res.menu[0])
          router.addRoutes(rout);
        }else{
          for(let i in res.list){
            let rout=changeMenu(res.list[i])
            list[i]=rout
            menu.push(res.menu[i-1])
            if(index==i){
              continue
            }
            router.addRoutes(rout);
            // console.log(res.list[i])
          }
          commit('SET_ROUTERSINDEX', index)
          localStorage.setItem("menuall", JSON.stringify(res.list));
        }
        commit('SET_ROUTERS',list)
        commit('SET_MENU',menu)
        commit('SET_NAME', res.web_name)
        commit('SET_INFO', res.info)
        commit('SET_IS_MUCH_SHOP', res.IS_MUCH_SHOP)
        if(res.info.account!=undefined)[
          commit('SET_MODEL', 'shop')
        ]
        if(res.web_logo!=undefined&&res.web_logo!=''){
          commit('SET_AVATAR', res.web_logo)
          commit('SET_LOGO', res.web_logo)
        }
        
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        localStorage.removeItem("menuall");
        localStorage.removeItem("menuindex");
        commit('SET_ROUTERS',[])
        commit('SET_INFO', [])
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    // })
  },

  // remove token
  delete_token({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  set_routers({ commit }, view) {
    commit('SET_ROUTERS', view)
  },
  set_routers_index({ commit }, view) {
    commit('SET_ROUTERSINDEX', view)
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

